/**
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 **/
const appconfig = require('../appconfig.js');
const fwlog = require('./fwlog.js');

const fwtool = {
  //访问api
  requestApi: function(api, params, method, headers, successcallback, failcallback, completecallback,app_this) {
    //导航显示加载图标
    wx.showNavigationBarLoading();

    if (method == ''||null == method) {
      //GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      method = 'POST';
    }

    //头部
    let header = {
        "accept": "application/json",
        // 'content-type': 'application/x-www-form-urlencoded',
        'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'
        // 'content-type': 'application/json',
        // 'content-type': 'multipart/form-data',
    };
    //追加参数
    if(headers){
        for(var key in headers){
            header[key] = headers[key];
        }
    }
    
    //输出日志
    fwlog.debug(api,'api');
    fwlog.debug(params,'params');
    fwlog.debug(headers,'headers');

    wx.request({
      url: api,
      data: params,
      header: header,
      responseType: 'text',
      method: method,
      dataType: 'json',
      success: function(res) {
        //输出日志
        fwlog.debug(res,'res');
        fwlog.debug(res.data,'res.data');

        if (res.statusCode !== 200) {
          fwtool.showModalInfo('网络请求错误');
          return;
        }
        if (typeof res.data !== 'object') {
          fwtool.showModalInfo('响应数据错误');
          return;
        }
        //检测是否需要登录
        if (app_this.globalData.wxmp_check_offline && res.data.caCode == appconfig.fwcode.nologin) {
          if(app_this.globalData.wxmp_login_enabled){
            //关闭登录提示
            app_this.globalData.wxmp_login_enabled = false;
            // 登录态失效, 重新登录
            wx.showModal({
              title: '友情提示',
              // content: '该帐号在其他设备登录！请重新登录',
              content: '登录已过期，请重新登录！',
              showCancel: true,
              cancelText: '暂不登录',
              confirmText: '马上登录',
              success: function(res) {
                if (res.confirm) {
                  try {
                    wx.clearStorageSync();
                    wx.clearStorage();
                    wx.navigateTo({
                      url: '/pages/basic/login?refresh=1',
                    });
                  } catch (e) {
                    fwlog.error(e);
                  }
                } else if (res.cancel) {
                  try {
                    wx.clearStorageSync();
                    wx.clearStorage();
                    wx.navigateTo({
                      url: '/pages/basic/login?refresh=1',
                    });
                  } catch (e) {
                    fwlog.error(e);
                  }
                  // //优化默认跳转界面
                  // let pages = getCurrentPages();
                  // if (pages.length) {
                  //   let currentPage = pages[0];
                  //   wx.reLaunch({
                  //     url: '/' + currentPage.route,
                  //   });
                  // } else {
                  //   wx.reLaunch({
                  //     url: '/pages/index/index',
                  //   });
                  // }
                }
              }
            });
          }
          return;
        }
        //执行成功回调
        successcallback && successcallback(res.data);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        //隐藏导航加载图标
        wx.hideNavigationBarLoading();
        completecallback && completecallback(res);
      }
    })
  },
  //信息弱提示
  showToastInfo: function(msg, mask, duration, successcallback, failcallback, completecallback) {
    if (null == duration || isNaN(duration) || duration == 0) {
      duration = 1500;
    }
    if (null == mask || typeof mask == 'undefined'){
      mask = false;
    }
    wx.hideToast();

    wx.showToast({
      title: msg,
      icon: 'none',
      duration: duration,
      mask: mask,
      success: function(res) {
        successcallback && setTimeout(function() {
          successcallback(res)
        }, duration);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //信息弹框提示
  showModalInfo: function(msg, successcallback, failcallback, completecallback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        successcallback && successcallback(res);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //确认框提示
  showModalConfirm: function(title, msg, cancelText, confirmText, successcallback, failcallback, completecallback) {
    if (title == '') {
      title = '信息提示';
    }
    if (cancelText == '') {
      cancelText = '取消';
    }
    if (confirmText == '') {
      confirmText = '确定';
    }

    wx.showModal({
      title: title,
      content: msg,
      showCancel: true,
      cancelText: cancelText,
      confirmText: confirmText,
      success: function(res) {
        successcallback && successcallback(res.confirm, res.cancel);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //比较版本
  compareVersion: function(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },
  //转换json为query参数(ES6)
  httpBuildQuery:function(jsonParam){
    return Object.keys(params).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
    }).join('&');
  },
  //格式化url字符串
  encodeJsonStr: function (jsonParam) {
    fwlog.debug(jsonParam,'传递Json参数');
    return encodeURIComponent(JSON.stringify(jsonParam));
  },
  //解析url字符串
  decodeJsonStr: function (jsonStr) {
    let tmpJson = JSON.parse(decodeURIComponent(jsonStr));
    fwlog.debug(tmpJson,'接收Json参数');
    return tmpJson;
  },
  //格式化url字符串
  encodeUrlJsonStr: function(webUrl) {
    let jsonParam = {
      url: webUrl
    };
    fwlog.debug(tmpJson,'传递url参数');
    return encodeURIComponent(JSON.stringify(jsonParam));
  },
  //解析url字符串
  decodeUrlJsonStr: function(jsonParam) {
    let jsonParamObject = JSON.parse(decodeURIComponent(jsonParam));
    fwlog.debug(jsonParamObject.url,'接收url参数');
    return jsonParamObject.url;
  },
  //过滤null值
  getNullFilter(param,defaultTxt=''){
    if(typeof param == 'object'){
        //为null
        if(param == null){
            return defaultTxt;
        }
        for(let key in param){
            if(param[key]==null){
                param[key] = defaultTxt;
            }
        }
    }else if(typeof param == 'array'){
        for(let i=0; i<param.length; i++){
            for(let key in param[i]){
                if(param[i][key]==null){
                    param[i][key] = defaultTxt;
                }
            }
        }
    }
    return param;
  },
  //设置自适应尺寸
  setAutoSize: function(callback) {
    //  高度自适应
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        callback && callback({
          cwidth: 750,          
          rpxRate: rpxR,
          cheight: (clientHeight * rpxR),
          pixelRatio: res.pixelRatio
        }, res);
      }
    });
  },
  //兼容多页，期中首页未加载满当前页面，未触发onReachBottom事件
  loadPageMore: function (tidName, callback) {
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        let winHeight = res.windowHeight;

        var query = wx.createSelectorQuery();
        query.select('#' + tidName).boundingClientRect();
        query.exec(function (qres) {
          if (qres[0].height < winHeight) {
            callback && callback();
          }
        });
      },
    });
  },
  //单页数据未满屏，自动加载第二页数据
  autoLoadMore: function(_this){
    if (1 == _this.data.dataPageNum && _this.data.dataPageTotal > 1) {
      fwtool.loadPageMore(_this.data.listContainerId, function () {
        _this.loadPageList(null);
      });
    }
  },
  //图片加载失败显示默认图
  //image中设置 binderror="bindImageError" data-index="0" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined'){
      if (typeof tmpIndex == 'undefined'){
        _this.setData({
          [tmpVariable]: tmpSrc
        });
      }else{
        _this.setData({
          [tmpVariable + '[' + tmpIndex+']']: tmpSrc
        });
      }
    }else{
      if (typeof tmpIndex == 'undefined') {
        _this.setData({
          [tmpVariable + '.' + tmpProperty]: tmpSrc
        });
      }else{
        _this.setData({
          [tmpVariable + '.' + tmpProperty + '[' + tmpIndex + ']']: tmpSrc
        });
      }
    }    
  },
  //列表图片加载失败显示默认图
  //image中设置 binderror="bindImageListError" data-index="{{index}}" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageListError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined') {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + ']']: tmpSrc
      });
    }else{
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '].' + tmpProperty]: tmpSrc
      });
    }    
  },
  //列表图片加载失败显示默认图
  //image中设置 binderror="bindTabImageListError" data-tabidx="{{tabsCurrentIndex}}" data-index="{{index}}" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindTabImageListError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpTabidx = evthleDataset.tabidx;
    let tmpIndex = evthleDataset.index;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined') {
      _this.setData({
        [tmpVariable + '[' + tmpTabidx + ']' + '[' + tmpIndex + ']']: tmpSrc
      });
    }else{
      _this.setData({
        [tmpVariable + '[' + tmpTabidx + ']' + '[' + tmpIndex + '].' + tmpProperty]: tmpSrc
      });
    }    
  },
  //列表嵌套列表图片加载失败显示默认图
  //image中设置 binderror="bindImageListToListError" data-index="{{index}}" data-index2="{{indexK}}" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageListToListError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpIndex2 = evthleDataset.index2;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined') {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '][' + tmpIndex2+']']: tmpSrc
      });
    } else {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '].' + tmpProperty + '[' + tmpIndex2+']']: tmpSrc
      });
    }
  },
  // 返回上N页
  navigateBackPage:function(pageLayerNum,callback){
    let pages = getCurrentPages();
    let targetPage = pages[pages.length - 1 - pageLayerNum];
    // targetPage.route
    wx.navigateBack({
      delta: pageLayerNum,
      success:function(){
        callback && callback(targetPage);
      }
    });
  },
  // 打开下一页，预设路径用'|'分隔
  navigateNextPage: function (navPath,callback) {
    let currentPathIsLast = false;

    if (navPath.length > 0 && (navPath.indexOf('|') != -1)) {
      let pages = getCurrentPages();
      let currentPage = pages[pages.length - 1];
      let currentPathIndex = -1;
      let paths = navPath.split('|');
      
      for (let i = 0; i < paths.length; i++) {
        if(paths[i].indexOf('?') != -1){
          if (paths[i].substring(0,paths[i].indexOf('?')) == '/' + currentPage.route) {
            currentPathIndex = i;
            break;
          }
        }else{
          if (paths[i] == '/' + currentPage.route) {
            currentPathIndex = i;
            break;
          }
        }
      }

      if (currentPathIndex > -1 && (paths.length > currentPathIndex + 1)) {
        wx.navigateTo({
          url: paths[currentPathIndex + 1],
        })
      }else{
        currentPathIsLast = (paths.length <= (currentPathIndex+1));
      }
    }
    callback && callback(currentPathIsLast);
  },
    //滚动页面到低部
    pageScrollToBottom: function (tidName, callback) {
        let _this = this;
        wx.getSystemInfo({
            success: function (res) {
            let winHeight = res.windowHeight;

            var query = wx.createSelectorQuery();
            query.select('#' + tidName).boundingClientRect(function(rect) {
                // 使页面滚动到底部
                   wx.pageScrollTo({
                    scrollTop: rect.height
                   })
              });
            query.exec(function (qres) {
                if (qres[0].height > winHeight) {
                    callback && callback();
                }
            });
            },
        });
    },
    //打开文件
    openDocument:function(weburl,callback){
        fwlog.debug(weburl,'weburl');

        if(!(weburl && weburl.length>0)){
            return;
        }
        //网络文件
        if(weburl.startsWith('http') || weburl.startsWith('https')){
            wx.downloadFile({
                url: weburl,
                success: function (res) {
                    fwlog.debug(res,'downloadFile');

                    const filePath = res.tempFilePath;
                    wx.openDocument({
                        filePath: filePath,
                        success: function (res) {
                            fwlog.debug(res,'openDocument');
                        },
                        fail: function (err) {
                            wx.showToast({
                                title: '不支持预览',
                              });
                        },
                        complete: function () {
                            callback && callback(filePath);
                        }
                    });
                }
            });
        }else{ //本地文
            wx.openDocument({
                filePath: weburl,
                success: function (res) {
                    
                },
                fail: function (err) {
                    wx.showToast({
                      title: '不支持预览',
                    });
                },
                complete: function () {
                    callback && callback(weburl);
                }
            });
        }
    },
    //删除文件
    unlinkDocument:function(localFilePath){
        if(localFilePath && localFilePath.length>0){
            let fsm = wx.getFileSystemManager();
            fsm.unlinkSync({
                filePath:localFilePath,
                success:function(res){
                },
                fail:function(err){
                },
            });
        }
    },
    //身份证号校验
    chkIdcard: function(code) {
        var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
        var tip = "";
        var pass= true;
    
        if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/i.test(code)){
            tip = "身份证号格式错误";
            pass = false;
        }
    
        else if(!city[code.substr(0,2)]){
            tip = "地址编码错误";
            pass = false;
        }
        else{
            //18位身份证需要验证最后一位校验位
            if(code.length == 18){
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                //校验位
                var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++)
                {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if(parity[sum % 11] != code[17]){
                    tip = "校验位错误,结尾是字母请注意大小写";
                    pass =false;
                }
            }
        }
        return [pass,tip]
    },
    //锁定未授权操作
    lockSetting:function(){
        //禁用转发按扭
        wx.hideShareMenu();
    },
    // 前置N页操作
    previousPageAction:function(pageLayerNum,callback){
        let pages = getCurrentPages();
        let targetPage = pages[pages.length - 1 - pageLayerNum];
        callback && callback(targetPage);
    }
}

module.exports = fwtool;